<?php


namespace app\api\library\order\orderPay;


use app\api\help\SendMsg;
use app\api\model\MallCollage;
use app\api\model\MallGoods;
use app\api\model\MallOrder;
use app\api\model\MallTradeRecordLog;
use app\api\model\MallUser;
use think\Exception;
use think\facade\Db;
use think\facade\Log;

class V
{
    public static function run($param)
    {
        $userId    = _checkEmptyParam($param[ 'userId' ], '用户ID不能为空');
        $openId    = _checkEmptyParam($param[ 'openId' ], '用户openId不能为空');
        $orderId   = _checkEmptyParam($param[ 'orderId' ], '订单ID不能为空');
        $addressId = _checkEmptyParam($param[ 'addressId' ], '收货地址ID不能为空');
        $address   = Db::name('mall_address')->where('id', $addressId)->find();
        if (empty($address)) {
            _outPut(204, [], '收货地址不存在');
        }
        $remark           = $param[ 'remark' ];
        $wechatPayAmount  = $param[ 'wechatPayAmount' ];
        $balancePayAmount = $param[ 'balancePayAmount' ];
        $where            = [
            ['id', '=', $orderId],
            ['user_id', '=', $userId],
            ['delete_time', '=', null],
        ];
        $order            = Db::name('mall_order')
            ->where($where)
            ->find();
        if (empty($order)) {
            _outPut(204, '', '订单不存在');
        }
        if ($wechatPayAmount + $balancePayAmount != $order[ 'order_price' ]) {
            _outPut(204, '', '订单金额异常');
        }
        if ($order[ 'order_status' ] != 0) {
            _outPut(204, '', '订单状态异常');
        }
        $balance = MallUser::where('id', $userId)->value('balance');
        if ($balance < $balancePayAmount) {
            _outPut(204, '', '余额不足以支付本次交易');
        }
        $joinNum = 0;
        //查询拼团人数
        if ( !empty($order[ 'u_collage_id' ])) {
            $collageNum = MallCollage::where('collage_id', $order[ 'u_collage_id' ])->value('collage_num');
            //已支付人数
            $joinNum = MallCollage::where('collage_id', $order[ 'u_collage_id' ])->value('join_num');
            if ($joinNum >= $collageNum) {
                Log::write($order);
                _outPut(204, '', '该拼团已完成拼团');
            }
        }
        if ($order[ 'u_collage_id' ] > 0) {
            $uCache = cache('uCollageId' . $order[ 'u_collage_id' ]);
            if ($uCache == 1) {
                _throwNewException('拼团繁忙');
            }
            cache('uCollageId' . $order[ 'u_collage_id' ], 1, 2);
        }
        try {
            //开启事务
            Db::startTrans();
            $cache = cache('orderId' . $orderId);
            if ($cache == 1) {
                _throwNewException('订单正在处理中');
            }
            cache('orderId' . $orderId, 1, 2);
            //修改订单支付余额
            $modOrder              = [
                'pay_balance' => $balancePayAmount,
                'address_id'  => $addressId,
                'remark'      => $remark,
                'phone'       => $address[ 'phone' ],
                'receiver'    => $address[ 'name' ],
                'pay_time'    => time(),
                'update_time' => time(),
            ];
            $modOrder[ 'address' ] = $address[ 'province' ] . $address[ 'city' ] . $address[ 'region' ] . '--' . $address[ 'detail' ];
            if ($balancePayAmount == $order[ 'order_price' ]) {
                //修改新手状态
                if (false === MallUser::where([['id', '=', $userId]])->update(['is_novice' => 0])) {
                    _throwNewException('订单支付失败5');
                }
                $modOrder[ 'order_status' ] = 10;
                $surBalance                 = $balance - $balancePayAmount;
                //减去余额
                if (false === MallUser::where([['id', '=', $userId]])->update(['balance' => $surBalance])) {
                    _throwNewException('订单支付失败');
                }
                //添加交易记录
                $tradeLogData = [
                    'trade_type'  => 2,
                    'amount'      => $balancePayAmount,
                    'balance'     => $surBalance,
                    'order_id'    => $orderId,
                    'user_id'     => $userId,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                if (false === MallTradeRecordLog::insert($tradeLogData)) {
                    _throwNewException('订单支付失败');
                }
                $collageId = MallOrder::resolveCollage($order, $userId);
                //邀请成功提醒短信
                if ($order[ 'u_collage_id' ] > 0) {
                    if ($joinNum + 1 == $collageNum) {
                        MallOrder::finishCollage($order[ 'u_collage_id' ]);
                    }
                }
                $modOrder[ 'collage_id' ] = $collageId;
                //查询用户邀请人
                $promotionId = MallUser::where([['id', '=', $userId]])->value('promotion_id');
                if ( !empty($promotionId)) {
                    MallOrder::resolvePromotion($userId, $order);
                }
            }
            
            if (false === MallOrder::where([['id', '=', $orderId]])->update($modOrder)) {
                _throwNewException('订单支付失败');
            }
            
            // 提交事务
            Db::commit();
        } catch (Exception $e) {
            // 回滚事务
            Db::rollback();
            _outPut(204, '', $e->getMessage());
        }
        
        if ($balancePayAmount == $order[ 'order_price' ]) {
            Db::name('mall_goods')->where('id', $order[ 'goods_id' ])->inc('sales', 1)->update();
            Db::name('mall_goods')->where('id', $order[ 'goods_id' ])->inc('virtual_sales', 1)->update();
            
            $res = [
                'payMode' => 0,
                'payInfo' => [],
            ];
            _outPut(200, $res);
        }
        
        $payData = [
            'order_no'     => $order[ 'order_no' ],                                            //订单编号
            'subject'      => $order[ 'goods_name' ] . ' - 拼团',                                //描述
            'total_amount' => $wechatPayAmount,                                                //支付金额
            //            'time_start'   => date('YmdHis', strtotime($parentOrder[ 'add_time' ])),
            //            'time_expire'  => date('YmdHis', strtotime($parentOrder[ 'add_time' ] . "+ 60 minutes")),//60分钟超时
        ];
        $payInfo = MallOrder::getWechatPayInfo($payData, $openId);
        Log::write($payInfo, 'notice');
        $res = [
            'payMode' => 1,
            'payInfo' => $payInfo,
        ];
        _outPut(200, $res);
    }
}